import axios from "axios";
import Cookie from 'js-cookie'
import router from '../router'
import Vue from "vue"
import store from '../store'

//管理端配置
const adminRequest = axios.create({
	baseURL:"http://localhost:8675/admin"
});

requestInterceptor(adminRequest);
responseInterceptor(adminRequest);

export function getAdminRequest(config) {
	return adminRequest(config);
}

//客户端配置
const apiRequeest = axios.create({
	baseURL:"http://localhost:8675/api"
});

requestInterceptor(apiRequeest);
responseInterceptor(apiRequeest);

export function getApiRequest(config){
	return apiRequeest(config);
}



function requestInterceptor(request) {
	//请求拦截器
	request.interceptors.request.use(config => {
	if (Cookie.get('token')) {
		config.headers["Authorization"] = 'Bearer ' + Cookie.get('token');
	}
		return config;
	}, error => {
		return Promise.reject(error);
	})
}

function responseInterceptor(request) {
	//响应拦截器
	request.interceptors.response.use(
		(response) => {
			if (response.data.status === 401) {
				Cookie.remove('token')
				store.resetVuex();
				Vue.prototype.$message.error("未登录，请先登录")
				router.push('/login')
			} else if (response.data.status === 200) {
				console.log(response.data);
			} else if (response.data.status === 403) {
				Vue.prototype.$message.error("权限不足")
			} else {
				console.log(response.data.msg);
			}
			return response
		},
		err => {
			// 失败响应
			if (err && err.response) {
				switch (err.response.status) {
					case 400:
						err.message = '请求无效，请检查参数是否正确!'
						break

					case 401:
						err.message = '未经授权，访问被拒!'
						break

					case 403:
						err.message = '拒绝访问!'
						break

					case 404:
						err.message = `地址不存在!`
						break

					case 408:
						err.message = '请求超时!'
						break

					case 500:
						err.message = '系统错误!'
						break

					case 501:
						err.message = '该方法未实现!'
						break

					case 502:
						err.message = '网管出错!'
						break

					case 503:
						err.message = '服务不可用!'
						break

					case 504:
						err.message = '网关请求超时'
						break

					case 505:
						err.message = 'HTTP版本不受支持'
						break

					default:
				}
				if (err.response.data.error) {
					err.message = err.response.data.error
				}
			}
		}
	)
}

